local skynet 		= require "skynet"
local socket 		= require "socket"
local show          = require "showmsg"
local manager  		= require "login.manager"
local login 		= require "login.login"
					  require "skynet.manager"

local CMD 	 = {}
local SOCKET = {}
local gate

function SOCKET.open(fd, addr)

	local session 		= socket:create_data()
	session.client_addr = addr
	session.func_parse  = login['parse']
	manager:add(fd, session)
	skynet.call(gate,"lua","forward",fd)
end  


local function close_agent(fd)

	local a = manager:get(fd)

	-- 保存账户信息未写
	--account:save(fd,sql)

	--管理器中移除 
	manager:remove(fd)

	if a then
		skynet.call(gate, "lua", "kick", fd)		
	end
end

function SOCKET.close(fd)

	skynet.error("socket close",fd)
	close_agent(fd)
end

function SOCKET.error(fd, msg)

	skynet.error("socket error",fd, msg)
	close_agent(fd)
end

-- 接收fd数据 
function SOCKET.forward(fd, msg, sz)

	local session = manager:get(fd)

	if not session then
		show:waning("收到无效的 fd = %s 消息" ,fd)
		return 
	end

	session.rsize = sz	
	session.type, session.name, session.rdata, session.response = socket:ser_host(msg, sz)
	session.func_parse(login, fd)
end 

function SOCKET.warning(fd, size)

	show:warning("套接字警告 fd = %d, size = %d", fd, size)
end

function SOCKET.data(fd, msg)
end

function CMD.start(conf)
	
	skynet.call(gate, "lua", "open", conf)
end

function CMD.init(conf)

	manager:init()
	socket:init()
end 

function CMD.close(fd)
	close_agent(fd)
end

skynet.start(function()

	skynet.dispatch("lua", function(session, source, cmd, subcmd, ...)
		if cmd == "socket" then
			local f = SOCKET[subcmd]
			f(...)
			-- socket api don't need return
		else
			local f = assert(CMD[cmd])
			skynet.ret(skynet.pack(f(subcmd, ...)))
		end
	end)

	gate = skynet.newservice("common/gate")
		   skynet.register("watchdog")   
end)
